
#include "ASpritesPattern.h"
#include "AXML.h"
#include "AString.h"

CASpritesPatternChild::CASpritesPatternChild()
{
	autorelease();
}

CASpritesPatternChild::~CASpritesPatternChild()
{
}

CASpritesPattern::CASpritesPattern()
{
	GUARD_FUNCTION();

	_children = new CAStringMap<CASpritesPatternChild>();
	autorelease();
}

CASpritesPattern::~CASpritesPattern(void)
{
	_Assert(_children);
	_children->release();
	_children = null;
}

int CASpritesPattern::initialize(const char* pszRes)
{
	GUARD_FUNCTION();

	_name = pszRes;

	CAXMLNode* pnode = CAXML::parse(pszRes, true);
	_Assert(null != pnode);

	pnode = pnode->firstnode("layout");
	_Assert(null != pnode);
	
	CAXMLNodes* pnodes;

	int index = 0;
	CCObject* pnodeobj;
	pnodes = pnode->nodes("child");
	CCARRAY_FOREACH(pnodes, pnodeobj)
	{
		GUARD_FIELD(loadchildren);

		CAXMLNode* psub = (CAXMLNode*)pnodeobj;
		_Assert(psub->hasAttr("name"));
		_Assert(psub->hasAttr("ref"));
		CAString name = psub->attr("name");
		CAString ref = psub->attr("ref");
		CCPoint pos;
		int usexy;
		CAString pose;
		if (psub->hasAttr("pos"))
		{
			CAStringUtils::toPoint(psub->attr("pos"), pos);
			usexy = 3;
		}
		else if (psub->hasAttr("xpos"))
		{
			CAStringUtils::toPoint(psub->attr("xpos"), pos);
			usexy = 1;
		}
		else if (psub->hasAttr("ypos"))
		{
			CAStringUtils::toPoint(psub->attr("ypos"), pos);
			usexy = 2;
		}
		else
		{
			_Assert(false);
		}
		
		if (psub->hasAttr("pose"))
		{
			pose = psub->attr("pose");
		}
		else
		{
			pose = "stand";
		}

		CAString gname;
		if (psub->hasAttr("gname"))
		{
			gname = psub->attr("gname");
		}
		else
		{
			char sz[16];
			sprintf(sz, "%d", index);
			gname = sz;
		}
		index++;

		//CASpriteModel* pmod = (CASpriteModel*)CACache::sharedCache().hit(ref.c_str(), CACHE_MODEL);
		//u must preload this model first
		//_Assert(pmod);

		CASpritesPatternChild* pc = new CASpritesPatternChild();
		pc->name = name;
		pc->ref = ref;
		pc->usexy = usexy;
		pc->pos = pos;
		pc->gname = gname;
		pc->pose = pose;
		_children->setObject(pc, name);
	}

	return 0;
}
